// pages/mine/mine.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    week: ["一", "二", "三", "四", "五", "六", "日"],//星期
    maxDayList: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],//一年12个月，每个月的天数，初始化都给平年
    nowYear: new Date().getFullYear(),//当前年份
    nowMonth: new Date().getMonth()+1,//当前月份
    nowDay: new Date().getDate(),//当天
    totalDay: [],//日历天数
    dateId : new Date().getFullYear().toString() +"/" + (new Date().getMonth()+1).toString() +"/"+ new Date().getDate().toString(),
    userInfo: {},
    dateList:[],
    name : '',
    phone:'',
    lastIdentity:"",
  },
/**
   * 切换年、月
   */
  changeDate(e) {
    let type = e.currentTarget.dataset.type;
    let nowYear = this.data.nowYear;
    let nowMonth = this.data.nowMonth;
    switch(type) {
      case "preYear": //上一年
        nowYear -= 1;
        this.setData({nowYear});
        break;
      case "preMonth": //上一月
        nowMonth -= 1;
        if(nowMonth <= 0) {
          nowMonth = 12;
          nowYear -= 1;
        }
        break;
      case "nextMonth": //下一月
        nowMonth += 1;
        if(nowMonth >= 13) {
          nowMonth = 1;
          nowYear += 1;
        }
        break;
      case "nextYear": //下一年
        nowYear += 1;
        break;
    }
    var startDate = nowYear + '-' + (nowMonth >= 10 ? nowMonth : '0' + nowMonth) + '-' + '01';
    var end = new Date(nowYear, nowMonth, 0).getDate();
    var endDay = nowYear + '-' + (nowMonth >= 10 ? nowMonth : '0' + nowMonth) + '-' + (end >=10 ? end : '0' + end);
    this.getHistoryDataIdentity(startDate,endDay)
    this.setData({nowYear, nowMonth});
    this.initCalendar();
  },

  /**
   * 初始化日历
   */
  initCalendar() {
    let maxDayList = this.data.maxDayList;
    let year = this.data.nowYear, month = this.data.nowMonth;
    if((year%4 == 0 && year%100 != 0) || year%400 == 0) {//计算当前年是不是闰年，规则：能被4整除且不被100整除，或者能被400整除的年份
      maxDayList[1] = 29;//2月份29天
    }else {//平年
      maxDayList[1] = 28;//2月份28天
    }
    this.setData({maxDayList});
    var firstDate = year + "-" + month + "-1";
    let firstDayWeek = new Date(firstDate.replace(/\-/g, "/")).getDay() ;//当前月的1号是星期几
  
    firstDayWeek = firstDayWeek > 0 ? firstDayWeek : 7;//星期日从0转成7
    var endDate = year + "-" + month + "-" +maxDayList[month - 1];
    let endDayWeek = new Date(endDate.replace(/\-/g, "/")).getDay();//当前月最后一天是星期几
    endDayWeek = endDayWeek > 0 ? endDayWeek : 7;//星期日从0转成7
    let beforArr = [], afterArr = [];//beforArr：本月1号之前需要补充上个月月尾几天，afterArr：本月尾补充下个月月初几天
    //求出补充的上个月的日子
    for(let i=0; i<firstDayWeek-1; i++) {//找出1号之前的空缺上个月的尾数日,比如今天是周三，则i=3-1, 取前两天的日子
      let deffTime = (i+1)*24*60*60*1000; //缺的天数的毫秒值
      var date = year + "-" + month + "-1";
      let firstTime = new Date(date.replace(/\-/g, "/")).getTime();//本月1号的毫秒值
      beforArr[i] = {otherMonth: true, day: new Date(firstTime - deffTime).getDate()};//从对应月份的尾数天开始存，比如31，30，29... 
    }
    beforArr = beforArr.reverse();//将补的上月的日子翻转
    //求出补充的下个月的日子
    for(let i=0; i<7-endDayWeek; i++) {//找出月尾对应的星期几，看看到周日还差几天就从下个月月初补几天
      afterArr[i] = {otherMonth: true, day: i+1};
    }
    let nowMonthArr = [];//当前月所有日子
    for(let i=0; i<maxDayList[month - 1]; i++) {
      nowMonthArr[i] = {day: i+1};
      if(year == new Date().getFullYear()) {//如果切换到了本年本月本日，则凸显今日
        if(month == new Date().getMonth() + 1) {
          if(new Date().getDate() == i+1) {
            nowMonthArr[i].today = true;
          }
        }
      }
    }
    let totalDayList = beforArr.concat(nowMonthArr).concat(afterArr);//将所有日期拼接
    let totalDay = [], arr = [];//totalDay:最终用来展示数据，arr：用来分割每一周的日子
    for(let i=0; i<totalDayList.length; i++) {
      arr.push(totalDayList[i]);
      if((i+1)%7 == 0) {//每7天存为一组
        totalDay.push(arr);
        arr = [];//存完清空
      }
    }
    this.setData({totalDay});
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    var openId= wx.getStorageSync('openid');
    var month = that.data.nowMonth;
    var day = that.data.nowDay;
    var time = that.data.nowYear +"-"+(month >=10 ? month : '0' + month)+"-"+(day >=10 ? day : '0' + day)
    that.initCalendar();
    that.getIdentity(openId,time);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var openId= wx.getStorageSync('openid');
    var time = this.data.dateId;
    var times = time.split("/");
    var finallyTime = times[0] +'-'+(times[1] > 10 ? time[1] :0 + times[1])+'-'+(times[2] > 10 ? times[2] :0 + times[2]);
    this.getIdentity(openId,finallyTime);
    this.initCalendar();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  getHistoryDataIdentity:function (startDate,endDate) {
    var that = this;
    var openId= wx.getStorageSync('openid');
    wx.request({
      //url: 'http://localhost:8066/record/historyData', 
      url: 'https://pnst.tsintell.com/record/historyData', 
      //url: 'http://124.71.238.22:8099/record/historyData',
      method: 'GET',
      data:{
        startDate : startDate,
        endDate : endDate,
        openId :openId
      },
      header: {//定死的格式，不用改，照敲就好
        'Content-Type': 'application/json',
        cookie: wx.getStorageSync("sessionId"),
      },
      success: function (res) {//这里写调用接口成功之后所运行的函数
        //console.log(res.data);//调出来的数据在控制台显示，方便查看
        var list  = res.data.data;
        for (var i=0; i < list.length;i++) {
          list[i] = list[i].replace(new RegExp("-",("gm")),"/"); 
        }
        that.setData({
          dateList: list,//res.data就是你调出来的所有数据（当然也可以在这里面自定义想要调用的数据），然后把值赋给resdata，之后对resdata进行处理即可，具体见wxml
        })
      },
      fail: function (res) {//这里写调用接口失败之后所运行的函数
       // console.log('.........fail..........');
       // console.log(res)
      }
    })
  },
   /**
   * 点击日期
   */
  checkeds:function(e){
    var that = this;
    var nowYear = that.data.nowYear.toString();
    var nowMonth = that.data.nowMonth.toString();
    var day = e.currentTarget.dataset.index;
    var date = e.currentTarget.dataset.date;
    // if(day){
    //    that.setData({
    //     dateId :nowYear + '/'+nowMonth + '/'+ day
    //    })
    // }
    //console.log(date)
    wx.navigateTo({
      url: '../record/record?time='+date
    })
    //that.getData(date);
  },

  changeMessage(){
    var name = this.data.name;
    var phone = this.data.phone;
    var sex = this.data.sex;
    var birthday = this.data.birthday;
    wx.navigateTo({
      url: '../person/person?name='+name+'&phone='+phone+'&sex='+sex+'&birthday='+birthday,
    })
  },
  getIdentity:function(openId,time){
    var that = this;
    wx.request({
      //url: 'http://localhost:8066/customer/getCustomerInfo',
      url: 'https://pnst.tsintell.com/customer/getCustomerInfo',
      //url: 'http://124.71.238.22:8099/customer/getCustomerInfo',
      method: 'get',
      data:{
        openId:openId
      },
      header: {//定死的格式，不用改，照敲就好
        'Content-Type': 'application/x-www-form-urlencoded',
        cookie: wx.getStorageSync("sessionId"),
      },
      success: function (res) {//这里写调用接口成功之后所运行的函数
        //console.log(res.data);//调出来的数据在控制台显示，方便查看
       if(res.data.code ==200){
        that.setData({
          name : res.data.customerDO.name,
          phone: res.data.customerDO.phone,
          sex:res.data.customerDO.sex,
          birthday:res.data.customerDO.birthday,
        })
        var nowYear = that.data.nowYear;
        var nowMonth = that.data.nowMonth;
        var startDate = nowYear + '-' + (nowMonth >= 10 ? nowMonth : '0' + nowMonth) + '-' + '01';
        var end = new Date(nowYear, nowMonth, 0).getDate();
        var endDay = nowYear + '-' + (nowMonth >= 10 ? nowMonth : '0' + nowMonth) + '-' + (end >=10 ? end : '0' + end);
        that.getHistoryDataIdentity(startDate,endDay)
        //that.getData(time);//获取当前日期数据
       }
      },
      fail: function (res) {//这里写调用接口失败之后所运行的函数
       // console.log('.........fail..........');
      //  console.log(res)
      }
    });
  },
})